var config = parent.parent.CONFIG,system=parent.parent.SYSTEM;
var isRefresh = false,ty_id = "";
var _limitMenu = system.MENULIMIT.BASE01;
var _menuParam = config.OPTIONLIMIT;
var queryurl = config.BASEPATH+'base/shop/page';
var pdata = {};

var Utils = {
	doQueryReward:function(rowid){
		var rowData = $('#grid').jqGrid('getRowData', rowid);
		commonDia = $.dialog({
			title : '奖励查询',
			content : 'url:'+config.BASEPATH+'base/shopreward/to_stat',
			data : {sp_code:rowData.sp_code},
			width : 520,
			height : 340,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:true,
			cancel:true
		});
	}
};

var handle = {
	operate: function(oper, id){//修改、新增
		var height = 340;
		var width = 540;
		var selected = window.parent.frames["treeFrame"].selectedTreeNode;
		if(oper == 'add'){
			title = '新增';
			url = config.BASEPATH+"base/shop/to_add";
			data = {oper: oper, callback:this.callback};
			if(selected != undefined){
				data.af_upcode = selected.id;
			}
		}else if(oper == 'edit'){
			title = '修改';
			url = config.BASEPATH+"base/shop/to_update?sp_id="+id;
			data = {oper: oper,callback: this.callback};
			if(selected != undefined){
				data.af_upcode = selected.id;
			}
		}else{
			return false;
		}
		$.dialog({
			title : title,
			content : 'url:'+url,
			data: data,
			width : width,
			height : height,
			max : false,
			min : false,
			cache : false,
			lock: true
		});
	},
	del: function(rowId){//删除
		if(rowId != null && rowId != ''){
		 	$.dialog.confirm('数据删除后无法恢复，确定要清除吗？', function(){
				$.ajax({
					type:"POST",
					url:config.BASEPATH+'base/shop/del',
					data:{"sp_id":rowId},
					cache:false,
					dataType:"json",
					success:function(data){
						if(undefined != data && data.stat == 200){
							Public.tips({type: 0, content : '删除成功!'});
							$('#grid').jqGrid('delRowData', rowId);
						}else{
							Public.tips({type: 1, content : '删除失败!'});
						}
					}
				});
			});
	   }else{
		   Public.tips({type: 3, content : '请选择数据!'});
	   }	
    },
    callback: function(data, oper, dialogWin){
		if(isRefresh){
			THISPAGE.reloadData();
		}
	},
	doState:function(obj,id){
    	var data = $("#grid").jqGrid('getRowData', id);
		var sp_state = data.sp_state,title="";
		if(sp_state == '1'){
			title = "确定要启用吗?";
			sp_state = "0";
		}else{
			title="确定要停用吗?"
			sp_state = "1";
		}
    	$.dialog.confirm(title, function(){
			$.ajax({
				type:"POST",
				url:config.BASEPATH+'base/shop/updateState',
				data:{"sp_id":id,"sp_state":sp_state},
				cache:false,
				dataType:"json",
				success:function(data){
					if(undefined != data && data.stat == 200){
						$("#grid").jqGrid("setRowData", id,{sp_state:sp_state,_sp_state:''});
						if(sp_state == "1"){
							$(obj).html("&#xe63c;")
							$(obj).removeClass("ui-icon-stop").addClass("ui-icon-begin");
							$(obj).attr("title","启用");
						}else{
							$(obj).html("&#xe60d;");
							$(obj).removeClass("ui-icon-begin").addClass("ui-icon-stop");
							$(obj).attr("title","停用");
						}
						Public.tips({type: 0, content : "状态修改成功!"});
					}else{
						Public.tips({type: 1, content : "状态修改失败!"});
					}
				}
			});
		});
    },
    initLock:function(){
        if (LOCK.isRightBrowser()) {
            if (LOCK.hadInstallEncrypt()) {
            } else {
                Public.tips({type: 2, content : "安全盾未安装!"});
                return;
            }
        } else {
            Public.tips({type: 2, content : "不支持该浏览器，请换支持的浏览器!"});
            return;
        }
	},
    doLock:function(obj){
    	 Public.tips({type: 2, content : "功能暂未启用!"});
    	 return;
		var lock = $(obj).attr('cs');
    	var rowId = $(obj).parent().parent().attr("id");
        if (lock == 0) { // 停用
        	handle.editLock(lock, rowId);
        } else {// 启用
            var sp_code = $("#grid").jqGrid('getRowData', id).sp_code;
            var store = system.COMPANYCODE + "~" + sp_code + "~" + 'shop';
            handle.initLock();
            var flag = LOCK.login(config.ENCRYPTPWD);
            if(flag){
            	var state = ENCRYPT.writeContent(store);
	            if (state == 0) {
	            	handle.editLock(lock, rowId);
	            } else {
	                $.dialog.tips("启用失败写入用户存储区失败，错误码：" + IA300_GetLastError(), 1, '32X32/fail.png');
	            }
            }else{
            	 $.dialog.tips("未检测到IA300加密狗!" , 1, '32X32/fail.png');
            }
        }
	},
	editLock:function(encrypt,si_id){
		 $.ajax({
            type: "get",
            url: config.BASEPATH + 'base/updateStoreEncrypt.action',
            data: 'si_id=' + si_id + '&SI_IsUseDog=' + encrypt,
            cache: false,
            dataType: "html",
            success: function (data) {
                if (data == "success") {
                    $.dialog.tips("保存数据成功", 1, '32X32/succ.png');
                    THISPAGE.reloadData(THISPAGE.initParam());
                } else {
                    $.dialog.tips("保存数据失败", 2, "32X32/fail.png");
                }
            }
        });
	},
	stateFmatter:function(val,opt,row){
		var _name = "停用";
		if(row.sp_state != 1){
			_name = "正常";
		}
		return _name;
	},
	operFmatter:function (val, opt, row) {
		var html_con = '<div class="operating" data-id="' +opt.rowId+ '">';
		html_con += '<i class="iconfont i-hand ui-icon-pencil" title="修改">&#xe60c;</i>';
		var _state = '&#xe60d;',_title = "停用",_class = "ui-icon-stop";
		if(row.sp_state != 0){
			_state = '&#xe63c;';
			_title = "启用";
			_class = "ui-icon-begin"
		}
		html_con += '<i class="iconfont i-hand '+_class+'" title="'+_title+'">'+_state+'</i>';
		html_con += '<i class="iconfont i-hand ui-icon-reward" title="奖励">&#x3435;</i>';
		html_con += '</div>';
		return html_con;
	},
	lockFmatter:function(val, opt, row){
		var btnHtml = "",type = row.sp_shop_type;
		//只有收银店铺才会有安全盾，因为给店铺加盾，收银就不用加了，使用一个就行了，也可以通过收银员加
		if(3 == type || 4 == type || 5 == type){
			if (row.sp_lock == '1') {
				btnHtml += '<input type="button" value="停用" class="btn_off" onclick="javascript:handle.doLock(this);" cs="0"/>';
			} else {
				btnHtml += '<input type="button" value="启用" class="btn_on" onclick="javascript:handle.doLock(this);" cs="1"/>';
			}
		}
		return btnHtml;
	}
};
var THISPAGE = {
	init:function (){
		this.initGrid();
		this.initEvent();	
	},
	initGrid:function(){
		var gridWH = Public.setGrid();
		var colModel = [
	    	{name: 'operate',label:'操作',width: 70, formatter: handle.operFmatter,align:'center', title: false,sortable:false},
	    	{name: '_sp_lock',label:'安全盾',index: '_sp_lock',align:'center', formatter:handle.lockFmatter,width:60},
	    	{name: 'sp_code',label:'编号',index: 'sp_code',width:80},
	    	{name: 'sp_name',label:'名称',index: 'sp_name',width:120},
	    	{name: 'ty_name',label:'类型',index: 'ty_name',width:100},
	    	{name: 'reward_count', label:'奖励个数',index: '', width: 80, sortable: false,align:'center'},
	    	{name: '_sp_state',label:'状态',index: '_sp_state',formatter:handle.stateFmatter,width:60},
	    	{name: 'sp_state',label:'状态隐藏值',index: 'sp_state',hidden:true},
	    	{name: 'sp_lock',label:'安全狗隐藏值',index: 'sp_lock',hidden:true},
	    	{name: 'sp_shop_type',label:'类型ID',index: 'sp_shop_type',hidden:true},
	    	{name: 'sp_end',label:'有效期',index: 'sp_end',width:100},
	    	{name: 'spi_man',label:'联系人',index: 'spi_man',width:80},
	    	{name: 'spi_mobile',label:'手机号',index: 'spi_mobile',width:100}
	    ];
		$('#grid').jqGrid({
            url:queryurl,			
			datatype: 'json',
			width: gridWH.w-12,
			height: gridWH.h-20,
			gridview: true,
			colModel: colModel,
			rownumbers: true,//行号
			pager: '#page',//分页
			page:1,
			pgbuttons:true,
			recordtext:'{0} - {1} 共 {2} 条',  
			multiselect:false,//多选
			viewrecords: true,
			rowNum:30,//每页条数
			cmTemplate: {sortable:true,title:false},
			shrinkToFit:false,//表格是否自动填充
			scroll: 1,//是否滚动
			jsonReader: {
				root: 'data.list',
				total: 'data.pageInfo.totalPage',
                page: 'data.pageInfo.currentPage',
                records: 'data.pageInfo.totalRow',
				repeatitems : false,
				id: 'sp_id'  //图标ID
			},
			loadComplete: function(data){
			},
			loadError: function(xhr, status, error){		
			}
	    });
	},
	reloadData:function(data){
		var param="?1=1";
		if(undefined != data){
			if(data.hasOwnProperty("shop_type")){
				ty_id = data.shop_type;
			}
		}
		param += "&ty_id="+ty_id;
		param += "&searchContent="+Public.encodeURI($("#SearchContent").val());
		$("#grid").jqGrid('setGridParam',{datatype:"json",page:1,url:queryurl+param}).trigger("reloadGrid");
	},
	initEvent:function(){
		$('#SearchContent').on('keyup',function(event){
			if (event.keyCode==13){
				$('#btn-search').click();
			}
		});
		//查询
		$('#btn-search').on('click', function(e){
			e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.SELECT)) {
				return ;
			}
			THISPAGE.reloadData();
		});
		//新增
		$('#btn-add').on('click', function(e){
			e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.INSERT)) {
				return ;
			}
			handle.operate('add');
		});
		//修改
		$('#grid').on('click', '.operating .ui-icon-pencil', function(e){
			e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.UPDATE)) {
				return ;
			}
			var id = $(this).parent().data('id');
			handle.operate('edit', id);
		});
		$('#grid').on('click', '.operating .ui-icon-stop', function(e){
			e.preventDefault();
			var id = $(this).parent().data('id');
			handle.doState(this,id);
		});
		$('#grid').on('click', '.operating .ui-icon-begin', function(e){
			e.preventDefault();
			var id = $(this).parent().data('id');
			handle.doState(this,id);
		});
		//删除
		$('#grid').on('click', '.operating .ui-icon-trash', function(e){
			e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.DELETE)) {
				return ;
			}
			var id = $(this).parent().data('id');
			handle.del(id);
		});
		$('#grid').on('click', '.operating .ui-icon-reward', function(e){
			e.preventDefault();
			var id = $(this).parent().data('id');
			Utils.doQueryReward(id);
		});
	}
}
THISPAGE.init();